package com.chushouya.order.service.admin.impl;

import com.chushouya.order.constants.OrderStatusEnum;
import com.chushouya.order.constants.OrderTypeEnum;
import com.chushouya.order.dao.entity.OrderAddressEntity;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.repository.OrderAddressRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dto.admin.order.OrderExportDTO;
import com.chushouya.order.dto.admin.order.OrderQuery;
import com.chushouya.order.service.admin.OrderExportService;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Beans;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.web.utils.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单导出服务实现
 */
@Service
@Slf4j
public class OrderExportServiceImpl implements OrderExportService {

    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderAddressRepository orderAddressRepository;

    @Override
    public void exportOrderPageResult(HttpServletResponse response, OrderQuery query) {
        try {
            // 查询订单数据
            PageResult<OrderEntity> pageResult = orderRepository.selectPageResult(query);
            List<OrderEntity> orderList = pageResult.getRows();
            
            if (orderList == null || orderList.isEmpty()) {
                log.warn("订单导出数据为空");
                throw Ex.business("暂无数据可导出");
            }

            log.info("订单导出,查询到订单数量:{}", orderList.size());
            List<OrderExportDTO> orderExportList = Beans.copyList(orderList,OrderExportDTO.class);
            orderExportList.forEach(item->{
                item.setOrderTypeText(OrderTypeEnum.getDesc(item.getOrderType()));
                item.setOrderStatusText(OrderStatusEnum.getDesc(item.getOrderStatus()));
            });
            // 导出Excel
            String fileName = Strings.format("订单数据导出-{}", Dates.dateTimeNow());
            new ExcelUtil<>(OrderExportDTO.class).exportExcel(response, orderExportList, fileName, "订单数据");
            
            log.info("订单导出成功,导出数量:{}", orderList.size());
        } catch (Exception e) {
            log.error("订单导出失败:{}", e.getMessage(), e);
            throw Ex.systemError("订单导出失败");
        }
    }
}
